
package gui;


import controllers.GUIController;
import hibernate.Schedule;
import hibernate.ScheduledActivity;
import hibernate.Activity;
import hibernate.User;
import java.awt.BorderLayout;
import java.awt.Color;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;

import java.awt.datatransfer.UnsupportedFlavorException;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import javax.swing.TransferHandler;

import javax.swing.*;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;

/**
 *
 * @author anjana
 */
public class Student_Schedule_DnD extends javax.swing.JInternalFrame {
    private static final long serialVersionUID = 1L;
    private static final int NONE = 0;
    JPanel pan1,pan2,pan3,pan4;
    JSeparator js;
    JButton[] buttons;
    ImageIcon img_blank;
    ImageIcon img_jpg;
    ImageIcon on_point_img;
    URL[] soundURL;
    Clip clip1,clip2;
    Line line;
    AudioInputStream ais;
    File[] soundfile;
    InputStream[] is;
    AudioClip ac;
    AudioInputStream audioInput;
    Dimension screenSize;
    int screenHeight;
    int screenWidth;
    JLabel stname_label;
    JLabel st_name;
    JLabel onpoint_lable, date_label;
    Date today;
    GroupLayout gr_layout;
    GroupLayout.SequentialGroup lr;
    JTextField stname_textfield;
    String act_name,img_name;
    JButton studentpagebutton;
    MouseHandler mouse;
    TransferHandler handler;
    KListener key;
    private GUIController guiC;
    private User currentStudent;
    Date date = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    private ScheduledActivity schedact = new ScheduledActivity();
    private Schedule s = new Schedule();
  
    private java.util.List<Schedule> curstud_schlist = new ArrayList();
    private java.util.List<ScheduledActivity> listschedact = new ArrayList();
    private java.util.List<Schedule> listsch = new ArrayList();
    private java.util.List<Activity> act = new ArrayList();
     
    private java.util.List<String> act_namearr = new ArrayList<>(); //-- no need worry about size. 
    private java.util.List<File> img_namearr = new ArrayList<>(); //-- no need worry about size. 
    
    final Student_Schedule_DnD obj_dnd = this;
    private File imageFile = new File("imageFile");
    private File soundFile = new File("soundFile");
    private int ctr;
   
   //Class Constructor
   //public Student_Schedule_DnD(GUIController m, User u) throws IOException
    public Student_Schedule_DnD(GUIController m, User u) throws IOException
   {	  //super(new BorderLayout());
	  super.setBackground(Color.blue);
          guiC = m; 
          currentStudent = u;
          String fd1,fd2;
          ctr = 1;
          
     curstud_schlist = currentStudent.getSchedules();
     System.out.println(curstud_schlist);
     
     fd1 = formatter.format(date);
     for (Iterator i = curstud_schlist.iterator(); i.hasNext();) {
             Schedule s =(Schedule) i.next();
             
             Date sch_start = s.getSchedCreatedOn();            //gets the start date of that schedule 
             String start1 = formatter.format(sch_start);           //chk with todays date  
             int result1 = fd1.compareTo(start1);
            
             schedact.setSchedStartDate(sch_start);               //checks if sched act date is same
             fd2 = formatter.format(sch_start);
             Date sched = schedact.getSchedStartDate();        
             String start2 = formatter.format(sched);  
             int result2 = fd2.compareTo(start2);
             
             if (result1 == 0 || result2 == 0)
             {   
                  System.out.println(schedact.getImageName()); 
                
             }
             System.out.println( listschedact.size()); 
             
              for (Iterator it = listschedact.iterator(); it.hasNext();)
              {    ScheduledActivity sa =(ScheduledActivity) it.next();
                  act_name = sa.getName();               //gets each name
                  imageFile = sa.getImage();          //gets each img name
                
                  act_namearr.add(ctr,act_name);
                  img_namearr.add(ctr,imageFile);
                  ctr = ctr + 1 ;
              }
            }
     
           buttons = new JButton[act_namearr.size()];
           
           key = new KListener();
           obj_dnd.setFocusable(true);
           obj_dnd.addKeyListener(key);
          
	    handler= new ButtonHandlerclass();
            mouse = new MouseHandler();
           
            // pan1 = new JPanel(new GridLayout(4,6));  
            pan1 = new JPanel(new GridLayout((act_namearr.size()+ (act_namearr.size() % 2 == 0 ? 0 : 1)) / 2, 4, 5, 5));
	    pan1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));    //creating border for individual panel
	    // pan2 = new JPanel(new GridLayout(4,6));
            pan2 = new JPanel(new GridLayout((act_namearr.size() + (act_namearr.size() % 2 == 0 ? 0 : 1)) / 2, 4, 5, 5));
	    pan2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));    //creating border for individual panel
            pan1.setBackground(Color.YELLOW);
	    pan2.setBackground(Color.YELLOW);
				
	    Dimension panelD = new Dimension(80,80);
	    stname_label = new JLabel("               STUDENT NAME:                ");     //student label
            st_name = new JLabel(currentStudent.getFirstName() + " " + currentStudent.getLastName());   
          
            date = new Date(); 
	    date_label = new JLabel();                     //date label
	    date_label.setText(date.toString());
	   
            pan3 = new JPanel(new BorderLayout());
	    pan3.setPreferredSize(panelD);
	    pan3.setMaximumSize(panelD);
	    pan3.add(stname_label,BorderLayout.WEST);
            pan3.add(st_name,BorderLayout.CENTER);
            
	    pan3.add(date_label,BorderLayout.EAST);
			    
            on_point_img = new ImageIcon(getClass().getResource("/Schedule_pics/OnPointlogo_edited.jpg"));  
	    pan4 = new JPanel(new BorderLayout());
	    JLabel onpoint_label = new JLabel(on_point_img); 
	    pan4.add(onpoint_label,BorderLayout.WEST);
           
	   /* screenSize = Toolkit.getDefaultToolkit().getScreenSize();   //full screen
	    screenHeight = screenSize.height;
            screenWidth = screenSize.width;
	    pan1.setSize(screenWidth / 2, screenHeight - (pan3.getHeight()+ pan4.getHeight()));
	    pan2.setSize(screenWidth -(pan1.getWidth()), screenHeight - (pan3.getHeight()+ pan4.getHeight())); */
	    
	   for (int i = 0; i < act_namearr.size(); i++)  
	    {   
	        // buttons[i] = new JButton(str_bnames[i]);
               buttons[i] = new JButton(act_namearr.get(i));
               // img_jpg = new ImageIcon(getClass().getResource("/Schedule_pics/" + str_bnames[i] + ".jpg"));
               buttons[i].setIcon(new ImageIcon(img_namearr.get(i).getAbsolutePath()));
	       buttons[i].setVerticalTextPosition(SwingConstants.BOTTOM); 
	       buttons[i].setHorizontalTextPosition(SwingConstants.CENTER);
	       buttons[i].addMouseListener(mouse);
	       buttons[i].addMouseMotionListener(mouse);
	       buttons[i].setTransferHandler(handler);
	       pan1.add(buttons[i]);
	    }  
	 
            // for (int i = 0; i< str_bnames.length; i++) 
            for (int i = 0; i< act_namearr.size(); i++)  
	     { 
	       buttons[i] = new JButton("Activity Completed");
	       img_blank = new ImageIcon("src/Schedule_pics/blank.jpg");
	       buttons[i].setIcon(img_blank); 
	       buttons[i].setVerticalTextPosition(SwingConstants.BOTTOM); 
	       buttons[i].setHorizontalTextPosition(SwingConstants.CENTER);
	       buttons[i].addMouseListener(mouse);
	       buttons[i].addMouseMotionListener(mouse);
	       buttons[i].setTransferHandler(handler);
	       Dimension d = buttons[i].getPreferredSize(); 
	       // make the buttons twice as tall as default 
	       Dimension big = new Dimension( (int)d.getWidth(),(int)d.getHeight()*2); 
	       buttons[i].setPreferredSize(big); 
	       pan2.add(buttons[i]);
	    }  
	       add(pan1,BorderLayout.WEST);
	       js = new JSeparator(JSeparator.VERTICAL);
	       js.setBackground(Color.ORANGE.darker());
	       add(js,BorderLayout.CENTER);
	       add(pan2,BorderLayout.EAST);
	       add(pan3,BorderLayout.NORTH);
	       add(pan4,BorderLayout.SOUTH);
	                
	       setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
       }//end of constructor

    
   public class KListener implements KeyListener
     {    @Override
           public void keyTyped(KeyEvent e) {
             //  throw new UnsupportedOperationException("Not supported yet.");
           }

           @Override
           public void keyPressed(KeyEvent e) {
              if (e.getKeyCode() == KeyEvent.VK_C)                                 //press ctrl , c together
              {    
                  obj_dnd.setFocusable(true); 
                  guiC.showGUI(new StudentView(guiC));
                  obj_dnd.dispose();
              }
             //  throw new UnsupportedOperationException("Not supported yet.");
           }
        @Override
           public void keyReleased(KeyEvent e) {
             //  throw new UnsupportedOperationException("Not supported yet.");
           }
       };
   
       //These are the Mouse Events
       class MouseHandler implements MouseListener,MouseMotionListener {
           
	 private static final long serialVersionUID = 1L;
         
         //============= Mouse Listener methods
          @Override
	 public void mouseClicked(MouseEvent e) {
            
           Object obj = e.getSource();
	    if( obj instanceof JButton) 
	    {    
	        
                JButton bclicked = (JButton)obj;
       	       String buttontext = bclicked.getText();
	       try {
		  audioInput = AudioSystem.getAudioInputStream(Student_Scheduled_Activities.class.getResource("/Wav_files/" + buttontext + ".WAV"));
                   } catch (  UnsupportedAudioFileException | IOException e3) {
		}
		try {
		    clip2 = AudioSystem.getClip();
		    } catch (LineUnavailableException e2) {}
		  					  
		try {
		   //clip.open(ais);
		   clip2.open(audioInput);
                  
                   
		   } catch (   LineUnavailableException | IOException e1) {
		  }
		if (clip2 != null) {
                   clip2.start();
                  
                    } else{
		   System.out.println("Couldn't load sound");
	        }
                
             
	    }//if
          
          }
         @Override
	 public void mouseEntered(MouseEvent e) {
	   // TODO Auto-generated method stub
	 }

	@Override
	public void mouseExited(MouseEvent e) {
	// TODO Auto-generated method stub
         }
	@Override
	public void mousePressed(MouseEvent e) {
	// TODO Auto-generated method stub
                      

         }
         @Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
	}
        //Mouse Motion Listener methods
           @Override
	public void mouseDragged(MouseEvent me) {
	// TODO Auto-generated method stub
	JComponent comp = (JComponent)me.getSource();
	 TransferHandler hand = comp.getTransferHandler();
	 hand.exportAsDrag(comp, me, TransferHandler.COPY);
	}
        @Override
	public void mouseMoved(MouseEvent arg0) {
	// TODO Auto-generated method stub
        }
     }
    /*  // Creates new JFrame "Activity Schedule"
     private static void createAndShowGUI() throws IOException {
				
	JFrame.setDefaultLookAndFeelDecorated(true);    //Make sure we have nice window decorations
	//JFrame.setDefaultLookAndFeelDecorated(false);   //Make sure we have nice window decorations
	final JFrame frame = new JFrame("Child's View Window - Activity Scheduled");              //Create and set up the window
	//addded new
	frame.setUndecorated(true);   //remove window decorations
	frame.getRootPane().setWindowDecorationStyle(NONE);
	frame.setExtendedState(JFrame.MAXIMIZED_BOTH);           //full screen
	//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   //closes when X is clicked
	//frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
	Student_Scheduled_Activities sv= new Student_Scheduled_Activities();       //Calls the class
	sv.setOpaque(true);                        //content panes must be opaque
        frame.setContentPane(sv);
        frame.pack();                               //Display the window.
	frame.setVisible(true);
			    // frame.setResizable(false);                  //cannot minimize
			    //frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
    }//end of createAndShow
			
    public static void main(String[] args) {
         javax.swing.SwingUtilities.invokeLater(new Runnable()       //Schedule a job for the event-dispatching thread:
	 {   @Override
    public void run() {
	      try {
		createAndShowGUI();
		} catch (IOException e) {// TODO Auto-generated catch block
                }
	      }
	 });
     }// end of main*/
	
       //ButtonHandler class
       class ButtonHandlerclass extends TransferHandler implements Transferable {
	        private static final long serialVersionUID = 1L;
		DataFlavor pictureFlavor = DataFlavor.imageFlavor;
		Image sourcePic;                    
		boolean shouldRemove;
                private Image img_gray;
		
                //-----------1st Method
            @Override
		public int getSourceActions(JComponent c) {
			return TransferHandler.COPY_OR_MOVE;
		}
		//---------------2nd Method
            @Override
		public boolean canImport(JComponent c, DataFlavor flavors[]) {          //c is component at the receiving end
		   if (c instanceof AbstractButton)                                    //DataFlavor is the type of data to be transfered 
		   {     
			AbstractButton button = (AbstractButton)c ;
			Icon icon = button.getIcon();
			ImageIcon comp_pic = ((ImageIcon) icon);
			String comp_pic_desc = comp_pic.getDescription();
			String img_blank_desc = img_blank.getDescription();
					      
			if (button.isEnabled() && comp_pic_desc.equals(img_blank_desc)) 
			{   
			  for (int i = 0; i < flavors.length; i++) {
				if (pictureFlavor.equals(flavors[i])) {
					 return true;
			         }
		         }
	                }
			}
		    return false;
		  }
		//-------------3rd Method
            @Override
		protected Transferable createTransferable(JComponent c) {            //c is at the source side component
		 sourcePic = null;
		 shouldRemove = true;
		if (c instanceof AbstractButton) 
		{  AbstractButton button = (AbstractButton)c ;
		   if (pan1.isAncestorOf(button))                           //checking if the button belongs to first panel
		    {
			Icon icon = button.getIcon();
			if (icon instanceof ImageIcon) 
			{     sourcePic = ((ImageIcon) icon).getImage();
			       return this;
			}
                   }
		}
	        return null;
		}
		//--------4th method
            @Override
		 public boolean importData(JComponent c, Transferable t)               // c is at receiving end
		 {                                                                    // t is the data to be transfered
		    if (c instanceof AbstractButton) {
		      AbstractButton button = (AbstractButton) c;
		      if (t.isDataFlavorSupported(pictureFlavor)) {
			 try {
			     sourcePic = (Image)t.getTransferData(pictureFlavor);
			     ImageIcon icon = new ImageIcon(sourcePic);
				button.setIcon(icon);
				return true;
			} catch (    UnsupportedFlavorException | IOException ignored) {
			}
		     }
		 }
		  shouldRemove = true;
		  return false;
		 }
		//Transferable methods
            @Override
		public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
		// TODO Auto-generated method stub
		  if (isDataFlavorSupported(flavor)){
			 return sourcePic;
		  }return null;
		}
            @Override
	        public DataFlavor[] getTransferDataFlavors() {
		// TODO Auto-generated method stub
		    return  new DataFlavor[] { pictureFlavor };
                }
            @Override
                public boolean isDataFlavorSupported(DataFlavor flavor) {
		   // TODO Auto-generated method stub
		   return  pictureFlavor.equals(flavor);
		}
            @Override
		protected void exportDone(JComponent c, Transferable t, int action) {      // c is source side component
		 if (c instanceof AbstractButton) {
		    AbstractButton button = (AbstractButton) c;
		 // try {
                  //     img_gray = ImageIO.read(Student_Scheduled_Activities.class.getResource("/Schedule_pics/Gray.jpg"));
		   //} catch (IOException e) {} 
		   if(action == MOVE) {
                      // sourcePic = img_gray;
                      // ImageIcon icon = new ImageIcon(sourcePic);
                      ImageIcon icon;
                      icon = new ImageIcon("src/Schedule_pics/blank.jpg");
                      sourcePic = icon.getImage();
                      
		      button.setIcon(icon);
		      button.setEnabled(false);
               	   }   
                  }
	         }
       }//end of Button handler class
        
    }


